#encoding=utf-8

from websys.models import LogRecharge,UserInfo,LogLogin,LogOnline
import time,datetime
from websys.view import cbyx_otherdata
#date_start='2017-10-25'
date_end =datetime.datetime.now().strftime('%Y-%m-%d')

end_date=time.mktime(time.strptime(str(date_end + ' 00:00:00'), '%Y-%m-%d %H:%M:%S'))

dtss = datetime.datetime.fromtimestamp(end_date)
c_time = datetime.timedelta(days=7)
date_starts=dtss -c_time
date_start=str(date_starts).split(' ')[0]

def getdata(filename):
    t_date_start = time.mktime(time.strptime(str(date_start + ' 00:00:00'), '%Y-%m-%d %H:%M:%S'))
    t_date_end = time.mktime(time.strptime(str(date_end + ' 00:00:00'), '%Y-%m-%d %H:%M:%S'))
    server_list=cbyx_otherdata.get_server_status()
    print 'server_list---------->>>',server_list
    b_date = t_date_start
    f = open("getdata/%s.txt" % str(filename), "w+")
    while b_date <= t_date_end:
        time_local = time.localtime(b_date)
        dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)

        dts = datetime.datetime.fromtimestamp(b_date)
        delta = datetime.timedelta(days=1)

        changed_time = dts + delta

        data_str='%s'%str(dt.split(' ')[0])+' , '
        for server in server_list:
            re_number = 0
            recharge = LogRecharge.objects.filter(create_time__gte=dt, create_time__lt=changed_time,server=server)
            for i in recharge:
                re_number += i.money
            recharge_count = recharge.distinct().values('uid').count()
            new_info = UserInfo.objects.filter(create_time__gte=dt, create_time__lt=changed_time,server=server)
            new_user_count=new_info.count()
            online_DAU_info = LogLogin.objects.filter(create_time__gte=dt, create_time__lt=changed_time,server=server)
            online_count=online_DAU_info.distinct().values('uid').count()
            data_str +=str(re_number)+' , '+str(new_user_count)+' , '+str(online_count)+' , '+str(recharge_count) + ' , '

        if b_date==t_date_end:
            print dt,'--------time----'
        f.write(data_str+'\n')
        Unixtime = time.mktime(time.strptime(changed_time.strftime('%Y-%m-%d %H:%M:%S'), '%Y-%m-%d %H:%M:%S'))
        b_date = Unixtime
    f.close()
    print '=================success-------------'


last_runner = ""
while 1:
    if last_runner != datetime.datetime.now().date():
        last_runner = datetime.datetime.now().date()
        print getdata(last_runner)
    else:
        pass

    time.sleep(300)